#include "ipmsgfileserver.h"

#include <unistd.h>
#include "filetransworker.h"

/**
 * @brief 构造函数, tcpsocketserver 在2425监听
 * @param parent 父对象
 */
IpMsgFileServer::IpMsgFileServer(QObject *parent) : QObject(parent)
{

    if(false == mServer.listen(QHostAddress::Any,2425))
    {
        qout<<"Listen to port 2425 filead";
        mFileServerListen = false;
        return;
    }
    else {
        mFileServerListen = true;
    }
    connect(&mServer,SIGNAL(newConnection()           ),
            this,    SLOT  (fileServerNewConnection()));
}

/**
 * @brief 获取到新的 TcpSocket
 */
void IpMsgFileServer::fileServerNewConnection()
{
    QTcpSocket *sock = mServer.nextPendingConnection();

    qout<<"new connection:"<<__FUNCTION__<<QThread::currentThreadId();
    if(nullptr == sock)
        return;

    qout<<"Client"  <<sock->peerAddress().toString()
        <<"Port"    <<sock->peerPort()
        <<"connected";

    connect(sock,SIGNAL(readyRead()),
            this,SLOT(fileServerReadyRead()));

    //connect(sock,SIGNAL(disconnected()),this,SLOT(fileServerSockDisconnect()));
    //connect(sock,SIGNAL(error(QAbstractSocket::SocketError)),
    //        this,SLOT(fileServerSockError(QAbstractSocket::SocketError)));

    mSocks.append(sock);
}

/**
 * @brief 文件准备读取
 */
void IpMsgFileServer::fileServerReadyRead()
{
    QByteArray buffer;
    QTcpSocket* readSocket = qobject_cast<QTcpSocket*>(sender());

    qout<<"Client"<<readSocket->peerAddress()<<"Port"<<readSocket->peerPort()<<"send data";

    buffer = readSocket->readAll();

    //readSocket->close();
    emit ipMsgFileServerDataReady(readSocket->peerAddress().toIPv4Address(), readSocket->peerPort(), buffer);
}

/**
 * @brief 文件服务器节点断开的槽函数,没有使用
 */
void IpMsgFileServer::fileServerSockDisconnect()
{
    QTcpSocket* srcSocket = qobject_cast<QTcpSocket*>(sender());
    qout<<"Client"<<srcSocket->peerAddress().toString()<<"Port"<<srcSocket->peerPort()<<"disconnected";
    qout<<"Tell send thread, stop send data to this client and delete sock and connect from queue";
    return;
}

/**
 * @brief 文件服务器socket错误槽函数,没有使用
 * @param error
 */
void IpMsgFileServer::fileServerSockError(QAbstractSocket::SocketError error)
{
    QTcpSocket* srcSocket = qobject_cast<QTcpSocket*>(sender());
    qout<<"Client"<<srcSocket->peerAddress().toString()<<"Port"<<srcSocket->peerPort()<<"error";
    qout<<"Tell send thread, stop send data to this client and delete sock and connect from queue";
    return;
}

/**
 * @brief 从 mSocks 中获取到 mSocks,公共函数,被外部调用
 * @param host 主机 IP    地址
 * @param port 主机 port  端口
 * @return
 */
QTcpSocket* IpMsgFileServer::fileServerSockMatch(quint32 host, quint16 port)
{
    for(int i =0; i< mSocks.count();i++)
    {
        if(mSocks.at(i)->peerAddress().toIPv4Address() == host
                && mSocks.at(i)->peerPort() == port)
            return mSocks.at(i);
    }
    return nullptr;
}




